package com.yunhuajinfu.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.yunhuajinfu.R;
import com.yunhuajinfu.activity.AboutActivity;
import com.yunhuajinfu.activity.AccountChongZhiActivity;
import com.yunhuajinfu.activity.AccountTiXianActivity;
import com.yunhuajinfu.activity.CenterFriendsActivity;
import com.yunhuajinfu.activity.HelpCenterActivity;
import com.yunhuajinfu.activity.MyBankCardActivity;
import com.yunhuajinfu.activity.MyHongBaoActivity;
import com.yunhuajinfu.activity.MyInvestmentActivity;
import com.yunhuajinfu.activity.SeetingsActivity;
import com.yunhuajinfu.activity.TradingRecordActivity;
import com.yunhuajinfu.activity.WebActivity;
import com.yunhuajinfu.activity.ZhenShiNameActivity;
import com.yunhuajinfu.base.BaseFragment;
import com.yunhuajinfu.entity.Huifu;
import com.yunhuajinfu.http.HttpCallBack;
import com.yunhuajinfu.http.HttpUtils;
import com.yunhuajinfu.mian.Config;
import com.yunhuajinfu.mian.MainActivity;
import com.yunhuajinfu.response.CitizenscertificationRes;
import com.yunhuajinfu.response.TiXianRes;
import com.yunhuajinfu.response.UserCenterIndexRes;
import com.yunhuajinfu.view.TitleBar;
import com.yunhuajinfu.view.banner.ConvenientBanner;
import com.yunhuajinfu.view.swipetoloadlayout.base.OnRefreshListener;
import com.yunhuajinfu.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人中心
 */
public class MyCenterFragment extends BaseFragment {
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.titlebar)
    TitleBar titleBar;
    @Bind(R.id.tv_allMoney)
    TextView tvAllMoney;
    @Bind(R.id.tv_waitCapital)
    TextView tvWaitCapital;
    @Bind(R.id.tv_income)
    TextView tvIncome;
    @Bind(R.id.tv_waitIncome)
    TextView tvWaitIncome;
    private MainActivity activity;
    private View view;
    //
    private ConvenientBanner convenientBanner;
    private UserCenterIndexRes res;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_more, container, false);
        activity = (MainActivity) getActivity();
        super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {

        titleBar.setTitleBar(R.mipmap.setting, "个人中心", 0);
        titleBar.setTitleBackgroundColor(getResources().getColor(R.color.bule));
        titleBar.setTitleBarLeftListener(this);

    }

    @Override
    protected void initView() {
        convenientBanner = (ConvenientBanner) view.findViewById(R.id.fragment_home_convenient_banner);
        mRefresh.setLoadMoreEnabled(false);
        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
//                 //获取首页收据
                getData();


            }
        });
    }

    @Override
    protected void setData() {
        getData();
    }

    @OnClick({R.id.lly_about, R.id.lly_wdtz, R.id.lly_wdyhk, R.id.tv_account_chongzhi, R.id.tv_account_tixian,
            R.id.lly_jyjl, R.id.lly_wdhb, R.id.lly_yqhy, R.id.lly_seeting, R.id.lly_helper})

    @Override
    protected void widgetClick(View view) {

        switch (view.getId()) {

            case R.id.titlebar_iv_back:

                startActivity(new Intent(getActivity(), SeetingsActivity.class));
                break;


            case R.id.titlebar_iv_rignt_img:
                Toast.makeText(getActivity(), "信息", Toast.LENGTH_SHORT).show();
                break;


            case R.id.lly_wdtz:   //我的投资

                Intent intent2 = new Intent(getActivity(), MyInvestmentActivity.class);
                startActivity(intent2);

                break;

            case R.id.lly_wdyhk:   //我的银行卡


                Intent intent = new Intent(getActivity(), MyBankCardActivity.class);
                startActivity(intent);


                break;

            case R.id.lly_jyjl:   //交易记录

                Intent intent1 = new Intent(getActivity(), TradingRecordActivity.class);
                startActivity(intent1);

                break;

            case R.id.lly_wdhb:

                startActivity(new Intent(getActivity(), MyHongBaoActivity.class));

                break;

            case R.id.lly_yqhy:

                startActivity(new Intent(getActivity(), CenterFriendsActivity.class));

                break;


            case R.id.lly_seeting:  //账户设置

                startActivity(new Intent(getActivity(), SeetingsActivity.class));

                break;

            case R.id.lly_about:     //关于


                Intent intent3 = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent3);
                break;


            case R.id.lly_helper:   //帮助中心

                startActivity(new Intent(getActivity(), HelpCenterActivity.class));

                break;


            case R.id.tv_account_chongzhi:    //充值  先判断

                sendtoRecharge();
                break;

            case R.id.tv_account_tixian:    //提现   先判断

                sendToWithdraw();

                break;


            default:
        }


    }

    /**
     * 提现
     */

    private void sendToWithdraw() {

        HttpParams params = new HttpParams();

        HttpUtils.post(Config.TOWITHDRAW, params, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    try {
                        TiXianRes res = new TiXianRes(new JSONObject(result.toString()));
                        if (null != res) {
                            Intent intent = new Intent(getActivity(), AccountTiXianActivity.class);
                            intent.putExtra("info", res);
                            startActivity(intent);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onError(String code, String message) {

                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();


                getAccountConfig();

            }
        });

    }


    /**
     * 账户充值
     */

    private void sendtoRecharge() {

        HttpParams params = new HttpParams();

        HttpUtils.post(Config.TORECHARGE, params, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    String availableMoney = result.optString("availableMoney");
                    Intent intent = new Intent(getActivity(), AccountChongZhiActivity.class);
                    intent.putExtra("availableMoney", availableMoney);
                    startActivity(intent);
                }
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                /**
                 * 实名认证   当充值出现  {"code":"-1","message":"请先注册汇付再进行此操作。"}
                 */
                getAccountConfig();

            }


        });

    }


    private void getAccountConfig() {

        HttpParams params = new HttpParams();

        HttpUtils.post(Config.ACCOUNTCONFIG, params, new HttpCallBack(getActivity(), "认证中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    try {
                        CitizenscertificationRes res = new CitizenscertificationRes(new JSONObject(result.toString()));
                        Huifu info = null;
                        if (null != res.getHuifu()) {
                            info = res.getHuifu();
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("capAcntNo", info.getCapAcntNo());
                            params.put("user_id_from", info.getUserIdFrom());
                            params.put("back_notify_url", info.getBackNotifyUrl());
                            params.put("city_id", info.getCityId());
                            params.put("email", info.getEmail());
                            params.put("cust_nm", info.getCustNm());
                            params.put("mchnt_cd", info.getMchntCd());
                            params.put("certif_id", info.getCertifId());
                            params.put("parent_bank_id", info.getParentBankId());
                            params.put("bank_nm", info.getBankNm());
                            params.put("mobile_no", info.getMobileNo());
                            params.put("mchnt_txn_ssn", info.getMchntTxnSsn());
                            params.put("signature", URLEncoder.encode(info.getSignature(), "UTF-8"));
                            //增加两个字段
                            params.put("ver", info.getVer());
                            params.put("page_notify_url", info.getPageNotifyUrl());
                            //
                            //去web加载页面
                            Intent intent = new Intent(getActivity(), WebActivity.class);
                            intent.putExtra("url", info.getGateWayUrl());
                            intent.putExtra("postData", makePostHTML(info.getGateWayUrl(), params));
//                            intent.putExtra("postData", HtmlFormUtil.makePostHTML(info.getGateWayUrl(),params))
                            intent.putExtra("titile_text", "实名认证");
                            try {
//                                intent.putExtra("params", HtmlFormUtil.paramMap2bytes(params));
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                        } else {
                            //
                            Intent intent = new Intent(getActivity(), ZhenShiNameActivity.class);
                            intent.putExtra("realName", res.getRealName());
                            intent.putExtra("cardNum", res.getCardNum());
                            startActivity(intent);


                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onError(String code, String message) {

                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });


    }

    /**
     * 获取数据
     */


    private void getData() {

        HttpParams params = new HttpParams();

        HttpUtils.post(Config.USERCENTERINDEX, params, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mRefresh.setRefreshing(false);
                if (null != result) {

                    try {
                        res = new UserCenterIndexRes(new JSONObject(result.toString()));
                        if (null != res) {
                            String waitCapital = res.getWaitCapital().toString().trim();
                            String waitIncome = res.getWaitIncome().toString().trim();
                            String income = res.getIncome().toString().trim();
                            tvAllMoney.setText(res.getAllMoney());
                            tvWaitCapital.setText("￥" + waitCapital);
                            tvWaitIncome.setText("￥" + waitIncome);
                            tvIncome.setText("￥" + formatNumber(Float.parseFloat(income)));
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String code, String message) {
                mRefresh.setRefreshing(false);
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 将float 类型保留两位数
     *
     * @param o
     * @return
     */
    public String formatNumber(Object o) {
        try {
            return null == o ? "" : String.format("%.2f", o);
        } catch (Exception e) {

            return "0.00";
        }
    }

    /**
     *   webview 提交form表单
     * @param apiURl
     * @param formData
     * @return
     */
    private String makePostHTML(String apiURl,Map<String,String> formData){
        String html = "<!DOCTYPE HTML><html><body><form id='sbform' action='%s' method='post'>%s</form><script type='text/javascript'>document.getElementById('sbform').submit();</script></body></html>";
        List<String> list = new ArrayList<>(formData.size());
        String input = "<input type='hidden' name='%s' value='%s'/>";
        for(Map.Entry<String,String> entry:formData.entrySet()){
            list.add(String.format(input,entry.getKey(),entry.getValue()));
        }
        return String.format(html, apiURl, StringUtils.join(list, "\n"));
    }

    /**
     * 更新数据
     */
    public  void updata(){
        getData();

    }

}
